<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { get as getBlogDetail, saveBlogVisitWithResult } from '@/api/blog'
  import type { Blog } from '@/types/api'
  import { ElMessage } from 'element-plus'
  import { MdPreview } from 'md-editor-v3'
  import 'md-editor-v3/lib/preview.css'
  import CommentTree from '@/views/articles/components/CommentTree.vue'

  const route = useRoute()
  const router = useRouter()

  const loading = ref(true)
  const post = ref<Blog | null>(null)
  const notFound = ref(false)
  const liking = ref(false)
  const hasLiked = ref(false)

  // 计算属性：格式化发布时间
  const formattedDate = computed(() => {
    if (!post.value?.pushTime) return ''
    return new Date(post.value.pushTime).toLocaleDateString('zh-CN')
  })

  // 计算属性：阅读时间估算
  const readTime = computed(() => {
    if (!post.value?.mkContent) return '1分钟'
    const wordsPerMinute = 300 // 中文阅读速度约 300 字/分钟
    const wordCount = post.value.mkContent.length
    const minutes = Math.ceil(wordCount / wordsPerMinute)
    return `${minutes}分钟`
  })

  const loadPost = async () => {
    try {
      loading.value = true
      const postId = route.params.id as string

      if (!postId) {
        notFound.value = true
        return
      }

      const response = await getBlogDetail({ id: postId })
      post.value = response

      // 记录查看行为
      await recordView(postId)
    } catch (error) {
      console.error('加载文章失败:', error)
      ElMessage.error('加载文章失败，请稍后重试')
      notFound.value = true
    } finally {
      loading.value = false
    }
  }

  // 记录查看行为
  const recordView = async (blogId: string) => {
    try {
      const result = await saveBlogVisitWithResult({
        blogId,
        type: 0, // 0表示查看
      })

      if (result.success) {
        // 可以在这里更新浏览量，如果需要的话
        if (post.value) {
          post.value.views = (post.value.views || 0) + 1
        }
      } else if (result.code === 816) {
        // 816表示已经查看过，不需要重复记录
      } else {
        console.warn('记录查看失败:', result.message)
      }
    } catch (error) {
      console.error('记录查看失败:', error)
      // 查看记录失败不影响用户体验，只记录错误
    }
  }

  const goBack = () => {
    router.push('/articles')
  }

  // 点赞功能
  const handleLike = async () => {
    if (!post.value || hasLiked.value || liking.value) {
      if (hasLiked.value) {
        ElMessage.warning('您已经点过赞了！')
      }
      return
    }

    try {
      liking.value = true

      const result = await saveBlogVisitWithResult({
        blogId: post.value.id,
        type: 1, // 1表示点赞
      })

      if (result.success) {
        // 点赞成功，更新页面数据
        post.value.likes = (post.value.likes || 0) + 1
        hasLiked.value = true
        localStorage.setItem(`liked_${post.value.id}`, 'true')
        ElMessage.success('点赞成功！')
      } else if (result.code === 816) {
        // 已经点赞过，不增加点赞数，但更新本地状态
        hasLiked.value = true
        localStorage.setItem(`liked_${post.value.id}`, 'true')
        ElMessage.info('您已经点过赞了！')
      } else {
        // 其他错误
        ElMessage.error(result.message || '点赞失败，请稍后重试')
      }
    } catch (error) {
      console.error('点赞失败:', error)
      ElMessage.error('点赞失败，请稍后重试')
    } finally {
      liking.value = false
    }
  }

  // 分享功能 - 复制当前页面链接
  const handleShare = async () => {
    try {
      const currentUrl = window.location.href

      // 优先使用现代 Clipboard API
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(currentUrl)
        ElMessage.success('链接已复制到剪贴板！')
      } else {
        // 降级方案：使用 execCommand
        const textArea = document.createElement('textarea')
        textArea.value = currentUrl
        textArea.style.position = 'fixed'
        textArea.style.left = '-999999px'
        textArea.style.top = '-999999px'
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()

        const success = document.execCommand('copy')
        textArea.remove()

        if (success) {
          ElMessage.success('链接已复制到剪贴板！')
        } else {
          throw new Error('复制失败')
        }
      }
    } catch (error) {
      console.error('复制链接失败:', error)
      ElMessage.error('复制失败，请手动复制页面链接')
    }
  }

  onMounted(() => {
    loadPost()

    // 检查是否已经点过赞
    const postId = route.params.id as string
    if (postId && localStorage.getItem(`liked_${postId}`)) {
      hasLiked.value = true
    }
  })
</script>

<template>
  <div class="article-detail-page">
    <div class="container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-skeleton">
        <div class="skeleton-header">
          <div class="skeleton-title"></div>
          <div class="skeleton-meta"></div>
        </div>
        <div class="skeleton-content">
          <div v-for="i in 10" :key="i" class="skeleton-line"></div>
        </div>
      </div>

      <!-- 文章未找到 -->
      <div v-else-if="notFound" class="not-found">
        <div class="not-found-icon">📝</div>
        <h2>文章未找到</h2>
        <p>抱歉，您访问的文章不存在或已被删除。</p>
        <button class="back-btn" @click="goBack">返回文章列表</button>
      </div>

      <!-- 文章内容 -->
      <article v-else-if="post" class="article-content">
        <!-- 文章头部 -->
        <header class="article-header">
          <div class="breadcrumb">
            <router-link to="/" class="breadcrumb-link">首页</router-link>
            <span class="breadcrumb-separator">></span>
            <router-link to="/articles" class="breadcrumb-link">文章</router-link>
            <span class="breadcrumb-separator">></span>
            <span class="breadcrumb-current">{{ post.title }}</span>
          </div>

          <h1 class="article-title">{{ post.title }}</h1>

          <div class="article-meta">
            <span v-if="post.category" class="category">{{ post.category.name }}</span>
            <span class="publish-date">{{ formattedDate }}</span>
            <span class="read-time">{{ readTime }}</span>
            <span class="views">{{ post.views || 0 }} 次阅读</span>
            <span class="likes">{{ post.likes || 0 }} 点赞</span>
          </div>

          <div v-if="post.tags && post.tags.length > 0" class="article-tags">
            <span v-for="tag in post.tags" :key="tag.id" class="tag">{{ tag.name }}</span>
          </div>
        </header>

        <!-- 文章正文 -->
        <div class="article-body">
          <MdPreview
            v-if="post.mkContent"
            :model-value="post.mkContent"
            :theme="'light'"
            :preview-theme="'github'"
            :code-theme="'atom'"
          />
        </div>

        <!-- 文章底部 -->
        <footer class="article-footer">
          <div class="article-actions">
            <button
              class="action-btn like-btn"
              :class="{ liked: hasLiked, loading: liking }"
              :disabled="liking"
              @click="handleLike"
            >
              <span v-if="liking">⏳</span>
              <span v-else-if="hasLiked">💖</span>
              <span v-else>❤️</span>
              {{ hasLiked ? '已点赞' : '点赞' }} ({{ post.likes || 0 }})
            </button>
            <button class="action-btn share-btn" @click="handleShare">🔗 分享</button>
          </div>

          <div class="back-to-list">
            <button class="back-btn" @click="goBack">← 返回文章列表</button>
          </div>
        </footer>

        <!-- 评论区域 -->
        <div class="comments-section">
          <CommentTree :blog-id="post.id" />
        </div>
      </article>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .article-detail-page {
    min-height: 100vh;
    padding: 2rem 0;
    background-color: var(--bg-color);
  }

  .article-content {
    max-width: 800px;
    margin: 0 auto;
    background: var(--bg-color);
    border-radius: var(--radius-xl);
    box-shadow: var(--shadow-md);
    overflow: hidden;
  }

  .article-header {
    padding: 2rem 2rem 1rem;
    border-bottom: 1px solid var(--border-color);
  }

  .breadcrumb {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 1.5rem;
    font-size: 0.9rem;
  }

  .breadcrumb-link {
    color: var(--primary-color);
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  .breadcrumb-separator {
    color: var(--text-tertiary);
  }

  .breadcrumb-current {
    color: var(--text-secondary);
  }

  .article-title {
    font-size: 2.5rem;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1.3;
    margin: 0 0 1.5rem 0;
  }

  .article-meta {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1rem;
    font-size: 0.9rem;
    color: var(--text-secondary);
    flex-wrap: wrap;
  }

  .category {
    background: var(--primary-color);
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: var(--radius-lg);
    font-size: 0.8rem;
    font-weight: 500;
  }

  .article-tags {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
  }

  .tag {
    background: var(--bg-secondary);
    color: var(--text-secondary);
    padding: 0.3rem 0.6rem;
    border-radius: var(--radius-md);
    font-size: 0.8rem;
    font-weight: 500;
  }

  .article-body {
    padding: 2rem;

    // MdPreview 组件样式自定义
    :deep(.md-editor-preview) {
      background: var(--bg-color);
      color: var(--text-primary);
      h1,
      h2,
      h3,
      h4,
      h5,
      h6 {
        color: var(--text-primary);
      }
      pre {
        background: var(--bg-secondary);
      }
      code {
        background: var(--bg-secondary);
      }
      summary {
        background-color: var(--bg-tertiary);
      }
      thead {
        tr {
          background-color: var(--bg-tertiary);
          color: var(--text-primary);
        }
      }
      tbody {
        tr {
          background-color: var(--bg-tertiary);
          color: var(--text-primary);
        }
      }
    }
  }

  .article-footer {
    padding: 2rem;
    border-top: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .article-actions {
    display: flex;
    gap: 1rem;
  }

  .action-btn {
    padding: 0.75rem 1.5rem;
    border: 1px solid var(--border-color);
    background: var(--bg-secondary);
    color: var(--text-secondary);
    border-radius: var(--radius-lg);
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.9rem;

    &:hover {
      border-color: var(--primary-color);
      color: var(--primary-color);
    }
  }

  .like-btn {
    &:hover {
      background: var(--primary-light);
    }

    &.liked {
      background: var(--primary-color);
      color: white;
      border-color: var(--primary-color);
    }

    &.loading {
      opacity: 0.7;
      cursor: not-allowed;
    }
  }

  .share-btn {
    &:hover {
      background: var(--success-light);
      border-color: var(--success-color);
      color: var(--success-color);
    }
  }

  .back-btn {
    padding: 0.75rem 1.5rem;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    color: var(--text-secondary);
    border-radius: var(--radius-lg);
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.9rem;

    &:hover {
      background: var(--primary-color);
      border-color: var(--primary-color);
      color: white;
    }
  }

  /* 评论区域样式 */
  .comments-section {
    background: transparent;
    padding: 2rem;
    margin-top: 2rem;
    border-top: 2px solid var(--border-color);
    position: relative;
  }

  .comments-section::before {
    content: '';
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60px;
    height: 2px;
    background: linear-gradient(90deg, var(--primary-color), #66b3ff);
    border-radius: 2px;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .article-detail-page {
      padding: 1rem 0;
    }

    .article-content {
      margin: 0 1rem;
      border-radius: var(--radius-lg);
    }

    .article-header {
      padding: 1.5rem 1.5rem 1rem;
    }

    .article-title {
      font-size: 2rem;
    }

    .article-body {
      padding: 1.5rem;
    }

    .article-footer {
      padding: 1.5rem;
      flex-direction: column;
      gap: 1rem;
      align-items: stretch;
    }

    .article-actions {
      justify-content: center;
    }

    .back-to-list {
      text-align: center;
    }

    .comments-section {
      padding: 1.5rem;
    }

    .article-meta {
      font-size: 0.8rem;
      gap: 0.75rem;
    }
  }
</style>
